package snev_cr;

import java.io.BufferedReader;

import java.io.FileReader;


import java.util.Date;
import java.util.concurrent.BlockingQueue;

public class Recolector implements Runnable {
	private String rss_name;
	BlockingQueue<SeedContainer> cola;
	long current_date = 0;

	@SuppressWarnings("deprecation")
	public Recolector(String rss, BlockingQueue<SeedContainer> queue)
	{
		rss_name = rss;
		cola = queue;
		BufferedReader input;
		
		String code_name;
		long valid_since;
		SeedContainer seed = new SeedContainer();

		try {
			input =  new BufferedReader(new FileReader(rss_name));
			String line = null;
			line = input.readLine();
			code_name = line;
			line = input.readLine();
			valid_since = Date.parse(line);

			input.close();

			input =  new BufferedReader(new FileReader(code_name));
			line = null;
			line = input.readLine();

		
			seed.seed1 = Integer.parseInt(line);
			seed.seed2 = -1;
			seed.fecha.setTime(valid_since + 5*60*1000);
		
			input.close();

			cola.put(seed);
			current_date = valid_since;

		} catch (Exception e) {
			System.out.println("tranceptor code: error al iniciar recolector ");
			System.out.println(e.toString());
		}

	}
	

	@SuppressWarnings("deprecation")
	public void run() 
	{

			while (true)
			{
				try {

					Thread.sleep(1000*60);
					
					BufferedReader input;
					
					String code_name;
					long valid_since;
					SeedContainer seed = new SeedContainer();
	
					input =  new BufferedReader(new FileReader(rss_name));
					String line = null;
					line = input.readLine();
					code_name = new String(line);
					line = input.readLine();
					valid_since = Date.parse(line);
					input.close();
	
					//busca la semilla y encola
					input =  new BufferedReader(new FileReader(code_name));
					line = null;
					line = input.readLine();
					seed.seed1 = Integer.parseInt(line);
					seed.seed2 = cola.peek().seed1;
					seed.fecha.setTime(valid_since + 5*60*1000);
					input.close();

					if (current_date == 0 || valid_since != current_date)
					{
						System.out.println("nueva semilla detectada:" + String.valueOf(seed.seed1));
						current_date = valid_since;
						cola.put(seed);
						if (cola.size()>1)
							cola.take();
					}
	
					
					

				} catch (Exception e) {
					System.out.println( e.toString());
					System.out.println("traceptor: error en recolector");
				}
	
			}	
	
	}

}
